import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:zhibao_flutter/api/wallet/wallet_entity.dart';
import 'package:zhibao_flutter/api/wallet/wallet_view_model.dart';
import 'package:zhibao_flutter/util/data/page_mini.dart';
import 'package:zhibao_flutter/util/func/smart_refresh.dart';
import 'package:zhibao_flutter/widget/appbar/commom_bar.dart';
import 'package:zhibao_flutter/widget/base/my_scaffold.dart';
import 'package:zhibao_flutter/widget/data/loading_view.dart';
import 'package:zhibao_flutter/widget/data/no_data_view.dart';
import 'package:zhibao_flutter/zone.dart';

import 'team_logic.dart';

class TeamPage extends StatefulWidget {
  @override
  State<TeamPage> createState() => _TeamPageState();
}

class _TeamPageState extends State<TeamPage> with TickerProviderStateMixin {
  final logic = Get.find<TeamLogic>();
  RxInt total = 0.obs;
  RxInt extra = 0.obs;

  @override
  void initState() {
    super.initState();
    logic.tabController = TabController(length: logic.tabs.length, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      appBar: CommomBar(
        title: "myTeam".tr,
      ),
      body: Column(
        children: [
          () {
            final heightOfContainer = 68.px;
            final heightOfContainerInner = 52.px;
            return Container(
              height: heightOfContainer,
              padding: EdgeInsets.all(8.px),
              margin: EdgeInsets.symmetric(horizontal: 15.px),
              decoration: BoxDecoration(
                color: Color(0xffF37135).withOpacity(0.1),
                borderRadius: BorderRadius.all(
                  Radius.circular(heightOfContainer / 2),
                ),
              ),
              child: TabBar(
                controller: logic.tabController,
                dividerHeight: 0,
                overlayColor: MaterialStateProperty.all(Colors.transparent),
                unselectedLabelColor: Color(0xff93989F),
                labelColor: Color(0xffFBFCFF),
                unselectedLabelStyle: TextStyle(
                  fontSize: 16.px,
                  fontWeight: MyFontWeight.medium,
                ),
                labelStyle: TextStyle(
                  fontSize: 16.px,
                  fontWeight: MyFontWeight.semBold,
                ),
                indicatorSize: TabBarIndicatorSize.label,
                indicatorPadding: EdgeInsets.all(0),
                indicator: BoxDecoration(
                  color: Color(0xffF37135),
                  borderRadius: BorderRadius.all(
                    Radius.circular(heightOfContainerInner / 2),
                  ),
                ),
                tabs: logic.tabs.map((e) {
                  return Container(
                    height: heightOfContainerInner,
                    width: 164.5.px,
                    alignment: Alignment.center,
                    child: Tab(text: e),
                  );
                }).toList(),
              ),
            );
          }(),
          SizedBox(height: 10.px),
          Expanded(
            child: TabBarView(
              controller: logic.tabController,
              children: logic.tabs.map((e) {
                return TeamTabPage(logic.tabs.indexOf(e), (totalFromApi) {
                  total.value = totalFromApi.total;
                  extra.value = totalFromApi.extra;
                });
              }).toList(),
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 26.5.px),
            child: Column(
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'totalTeamMembers'.tr,
                      style: TextStyle(
                        color: Color(0xff171616),
                        fontSize: 12.px,
                        fontWeight: MyFontWeight.bold,
                      ),
                    ),
                    Obx(
                      () => Text(
                        '${extra.value}${'people'.tr}',
                        style: TextStyle(
                          color: Color(0xffF37135),
                          fontSize: 12.px,
                          fontWeight: MyFontWeight.bold,
                        ),
                      ),
                    )
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      'totalDirectReferrals'.tr,
                      style: TextStyle(
                        color: Color(0xff171616),
                        fontSize: 12.px,
                        fontWeight: MyFontWeight.bold,
                      ),
                    ),
                    Obx(
                      () => Text(
                        '${total.value}${'people'.tr}',
                        style: TextStyle(
                          color: Color(0xffF37135),
                          fontSize: 12.px,
                          fontWeight: MyFontWeight.bold,
                        ),
                      ),
                    )
                  ],
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}

class TeamTabPage extends StatefulWidget {
  final int index;
  final Function(TeamEntityTotalData totalModel) onTotal;

  TeamTabPage(this.index, this.onTotal);

  @override
  State<TeamTabPage> createState() => _TeamTabPageState();
}

class _TeamTabPageState extends State<TeamTabPage> with PageMiniAbs, PageMini {
  List<TeamEntity> dataList = [];

  @override
  void initState() {
    super.initState();
    refreshHandle();
  }

  Future getData() async {
    // active
    // integer($int32)
    //   (query)
    // 激活 0:未激活 1激活 null: 获取全部
    // 激活就是有1级的用户，默认是0级，要充值等操作然后手动升级。
    final int? active = widget.index == 0 ? null : 1;

    final value =
        await walletViewModel.userMyTeam(null, active: active, page: goPage);
    if (value.data == null) {
      setLoadOk();
      return;
    }
    TeamEntityTotalData totalData = value.data!;

    if (goPage == 1) {
      dataList = totalData.dataList;
    } else {
      dataList.addAll(totalData.dataList);
    }
    if (totalData.dataList.isEmpty ||
        totalData.dataList.length < PageMini.perPage) {
      hasNextPage = false;
      refreshController.loadNoData();
    }
    setLoadOk();
    if (widget.index == 0) {
      widget.onTotal(totalData);
    }
  }

  /*
  * 刷新处理
  * */
  Future refreshHandle() async {
    goPage = 1;
    await getData();
    refreshController.refreshCompleted();
  }

  /*
  * 加载处理
  * */
  Future loadingHandle() async {
    goPage++;
    await getData();
    refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return MySmartRefresh(
      controller: refreshController,
      onRefresh: () async {
        return refreshHandle();
      },
      onLoading: () async {
        return loadingHandle();
      },
      child: () {
        if (!isLoadOk) {
          return const LoadingView();
        }
        if (!listNoEmpty(dataList)) {
          return NoDataView();
        }
        return ListView.builder(
          itemCount: dataList.length,
          padding: EdgeInsets.symmetric(horizontal: 15.px),
          itemBuilder: (context, index) {
            return TeamItem(dataList[index], widget.index);
          },
        );
      }(),
    );
  }

  @override
  void update([List<Object>? ids, bool condition = true]) {
    if (mounted) setState(() {});
  }
}

class TeamItem extends StatefulWidget {
  final TeamEntity entity;
  final int tabIndex;

  TeamItem(this.entity, this.tabIndex);

  @override
  State<TeamItem> createState() => _TeamItemState();
}

class _TeamItemState extends State<TeamItem> {
  RxBool showDetail = false.obs;

  @override
  Widget build(BuildContext context) {
    return InkwellWithOutColor(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 15.px, vertical: 10.px),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10.px))),
        margin: EdgeInsets.symmetric(
          vertical: 10.px,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Obx(() {
                  return Text(
                    showDetail.value ? (widget.entity.username ?? "") : "****",
                    style: TextStyle(
                      color: Color(0xff171616),
                      fontSize: 16.px,
                      fontWeight: MyFontWeight.bold,
                    ),
                  );
                }),
                SizedBox(width: 10.px),
                Container(
                  height: 16.px,
                  padding: EdgeInsets.symmetric(horizontal: 6.px),
                  decoration: BoxDecoration(
                    color: Color(0xffF37135),
                    borderRadius: BorderRadius.all(
                      Radius.circular(16.px),
                    ),
                  ),
                  child: Row(
                    children: [
                      SvgPicture.asset(
                        "assets/images/mine/ic_team_diamond.svg",
                        width: 12.px,
                      ),
                      SizedBox(width: 3.px),
                      Text(
                        'V${widget.entity.grade ?? "0"}',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12.px,
                        ),
                      ),
                    ],
                  ),
                ),
                Spacer(),
                Obx(() {
                  return SvgPicture.asset(
                      'assets/images/login/ic_eye_grey_${showDetail.value ? "open" : "close"}.svg');
                })
              ],
            ),
            SizedBox(height: 5.px),
            Text(
              '${'registrationTime'.tr}:${MyDate.formatTimeStampParse(widget.entity.createTime ?? "0")}',
              style: TextStyle(color: Color(0xff999999), fontSize: 12.px),
            ),
            SizedBox(height: 5.px),
            Obx(
              () => Text(
                // 【feb 27 2024】
                // 我的邀请，已激活列表手机号/邮箱码隐藏
                // 【feb 28 2024】
                // 我的团队所有tab的手机号/邮箱都隐藏中间4位。
                // [Mar 27 2024]
                //  [x] 我的团队：点击眼睛图标，可以显示完整号码，默认还是掩码显示
                '${'phoneOrEmail'.tr}:${showDetail.value ? (widget.entity.phone ?? "") : hidePhone(widget.entity.phone ?? "")}',
                style: TextStyle(color: Color(0xff999999), fontSize: 12.px),
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        showDetail.value = !showDetail.value;
      },
    );
  }
}
